﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.CompilerServices;

using ConstructionBidOnline.DAL;
using ConstructionBidOnline.DAL.dsDirectoryListTableAdapters;
using ConstructionBidOnline.Common;

namespace ConstructionBidOnline.Biz
{
    /// <summary>
    /// Directory Business Object
    /// </summary>

    public class Directory : BOBase
    {
        #region Construction / Disposal

        /// <summary>
        /// Default constructor.
        /// </summary>
        protected Directory() { }

        #endregion

        #region Public Properties

        #region Instance Properties

        /// <summary>
        /// PKID of the DirectoryList.
        /// </summary>
        public int UserID
        {
            get { return _userID; }
            set
            {
                if (_userID != value)
                {
                    if (OnPropertyChanging("UserID", _userID, value))
                    {
                        int oldValue = _userID;
                        _userID = value;

                        OnPropertyChanged("UserID", oldValue, value);
                    }
                }
            }
        }  private int _userID = -1;



        /// <summary>
        /// EmailAddress.
        /// </summary>
        public string EmailAddress
        {
            get { return _emailaddress; }
            set
            {
                if (_emailaddress != value)
                {
                    if (OnPropertyChanging("EmailAddress", _emailaddress, value))
                    {
                        string oldValue = _emailaddress;
                        _emailaddress = value;
                        OnPropertyChanged("EmailAddress", oldValue, value);
                    }
                }
            }
        }  private string _emailaddress = null;






        /// <summary>
        /// Telephone Number
        /// </summary>
        public string TelephoneNumber
        {
            get { return _telephonenumber; }
            set
            {
                if (_telephonenumber != value)
                {
                    if (OnPropertyChanging("TelephoneNumber", _telephonenumber, value))
                    {
                        string oldValue = _telephonenumber;
                        _telephonenumber = value;
                        OnPropertyChanged("TelephoneNumber", oldValue, value);
                    }
                }
            }
        }  private string _telephonenumber = null;


        /// <summary>
        /// MobileNumber.
        /// </summary>
        public string MobileNumber
        {
            get { return _mobilenumber; }
            set
            {
                if (_mobilenumber != value)
                {
                    if (OnPropertyChanging("MobileNumber", _mobilenumber, value))
                    {
                        string oldValue = _mobilenumber;
                        _mobilenumber = value;
                        OnPropertyChanged("MobileNumber", oldValue, value);
                    }
                }
            }
        }  private string _mobilenumber = null;


        /// <summary>
        /// Fax Number.
        /// </summary>
        public string FaxNumber
        {
            get { return _faxnumber; }
            set
            {
                if (_faxnumber != value)
                {
                    if (OnPropertyChanging("FaxNumber", _faxnumber, value))
                    {
                        string oldValue = _faxnumber;
                        _faxnumber = value;
                        OnPropertyChanged("FaxNumber", oldValue, value);
                    }
                }
            }
        }  private string _faxnumber = null;


        /// <summary>
        /// FirstName.
        /// </summary>
        public string FirstName
        {
            get { return _firstname; }
            set
            {
                if (_firstname != value)
                {
                    if (OnPropertyChanging("FirstName", _firstname, value))
                    {
                        string oldValue = _firstname;
                        _firstname = value;
                        OnPropertyChanged("FirstName", oldValue, value);
                    }
                }
            }
        }  private string _firstname = null;


        /// <summary>
        /// LastName.
        /// </summary>
        public string LastName
        {
            get { return _lastname; }
            set
            {
                if (_lastname != value)
                {
                    if (OnPropertyChanging("LastName", _lastname, value))
                    {
                        string oldValue = _lastname;
                        _lastname = value;
                        OnPropertyChanged("LastName", oldValue, value);
                    }
                }
            }
        }  private string _lastname = null;





        /// <summary>
        /// WebSiteUrl.
        /// </summary>
        public string WebSiteUrl
        {
            get { return _websiteurl; }
            set
            {
                if (_websiteurl != value)
                {
                    if (OnPropertyChanging("WebSiteUrl", _websiteurl, value))
                    {
                        string oldValue = _websiteurl;
                        _websiteurl = value;
                        OnPropertyChanged("WebSiteUrl", oldValue, value);
                    }
                }
            }
        }  private string _websiteurl = null;



        /// <summary>
        /// Business Logo.
        /// </summary>
        public string BusinessLogo
        {
            get { return __businesslogo; }
            set
            {
                if (__businesslogo != value)
                {
                    if (OnPropertyChanging("BusinessLogo", __businesslogo, value))
                    {
                        string oldValue = __businesslogo;
                        __businesslogo = value;
                        OnPropertyChanged("BusinessLogo", oldValue, value);
                    }
                }
            }
        }  private string __businesslogo = null;


        /// <summary>
        /// Business Description.
        /// </summary>
        public string BusinessDescription
        {
            get { return __businessdescription; }
            set
            {
                if (__businessdescription != value)
                {
                    if (OnPropertyChanging("BusinessDescription", __businessdescription, value))
                    {
                        string oldValue = __businessdescription;
                        __businessdescription = value;
                        OnPropertyChanged("BusinessDescription", oldValue, value);
                    }
                }
            }
        }  private string __businessdescription = null;


        /// <summary>
        /// AddressLine1.
        /// </summary>
        public string AddressLine1
        {
            get { return _addressline1; }
            set
            {
                if (_addressline1 != value)
                {
                    if (OnPropertyChanging("AddressLine1", _addressline1, value))
                    {
                        string oldValue = _addressline1;
                        _addressline1 = value;
                        OnPropertyChanged("AddressLine1", oldValue, value);
                    }
                }
            }
        }  private string _addressline1 = null;


        /// <summary>
        /// AddressLine2.
        /// </summary>
        public string AddressLine2
        {
            get { return _addressline2; }
            set
            {
                if (_addressline2 != value)
                {
                    if (OnPropertyChanging("AddressLine2", _addressline2, value))
                    {
                        string oldValue = _addressline2;
                        _addressline2 = value;
                        OnPropertyChanged("AddressLine2", oldValue, value);
                    }
                }
            }
        }  private string _addressline2 = null;


        /// <summary>
        /// City.
        /// </summary>
        public string City
        {
            get { return _city; }
            set
            {
                if (_city != value)
                {
                    if (OnPropertyChanging("City", _city, value))
                    {
                        string oldValue = _city;
                        _city = value;
                        OnPropertyChanged("City", oldValue, value);
                    }
                }
            }
        }  private string _city = null;


        /// <summary>
        /// State.
        /// </summary>
        public string State
        {
            get { return _state; }
            set
            {
                if (_state != value)
                {
                    if (OnPropertyChanging("State", _state, value))
                    {
                        string oldValue = _state;
                        _state = value;
                        OnPropertyChanged("State", oldValue, value);
                    }
                }
            }
        }  private string _state = null;


        /// <summary>
        /// Country.
        /// </summary>
        public string Country
        {
            get { return _country; }
            set
            {
                if (_country != value)
                {
                    if (OnPropertyChanging("Country", _country, value))
                    {
                        string oldValue = _country;
                        _country = value;
                        OnPropertyChanged("Country", oldValue, value);
                    }
                }
            }
        }  private string _country = null;


        /// <summary>
        /// ZipCode.
        /// </summary>
        public string ZipCode
        {
            get { return _zipcode; }
            set
            {
                if (_zipcode != value)
                {
                    if (OnPropertyChanging("ZipCode", _zipcode, value))
                    {
                        string oldValue = _zipcode;
                        _zipcode = value;
                        OnPropertyChanged("ZipCode", oldValue, value);
                    }
                }
            }
        }  private string _zipcode = null;



        /// <summary>
        /// True iff the User got Vissible and email got verified (i.e. to be used in the application).
        /// </summary>
        public bool IsVissible
        {
            get { return __isVissible; }
            set
            {
                if (__isVissible != value)
                {
                    if (OnPropertyChanging("IsVissible", __isVissible, value))
                    {
                        bool oldValue = __isVissible;
                        __isVissible = value;
                        OnPropertyChanged("IsVissible", oldValue, value);
                    }
                }
            }
        }  private bool __isVissible = false;


        /// <summary>
        /// True iff the User got Featured (i.e. to be used in the application).
        /// </summary>
        public bool IsFeatured
        {
            get { return _isFeatured; }
            set
            {
                if (_isFeatured != value)
                {
                    if (OnPropertyChanging("IsFeatured", _isFeatured, value))
                    {
                        bool oldValue = _isFeatured;
                        _isFeatured = value;
                        OnPropertyChanged("IsFeatured", oldValue, value);
                    }
                }
            }
        }  private bool _isFeatured = false;



        /// <summary>
        /// True iff the User got Featured and pays his featured fees(i.e. to be used in the application).
        /// </summary>
        public bool IsFeaturedFeesGiven
        {
            get { return _isFeaturedFeesGiven; }
            set
            {
                if (_isFeaturedFeesGiven != value)
                {
                    if (OnPropertyChanging("IsFeaturedFeesGiven", _isFeaturedFeesGiven, value))
                    {
                        bool oldValue = _isFeaturedFeesGiven;
                        _isFeaturedFeesGiven = value;
                        OnPropertyChanged("IsFeaturedFeesGiven", oldValue, value);
                    }
                }
            }
        }  private bool _isFeaturedFeesGiven = false;


        /// <summary>
        /// True iff the Admin has made this DirectoryList Active (i.e. to be used in the application).
        /// </summary>
        public bool IsActive
        {
            get { return _isActive; }
            set
            {
                if (_isActive != value)
                {
                    if (OnPropertyChanging("IsActive", _isActive, value))
                    {
                        bool oldValue = _isActive;
                        _isActive = value;
                        OnPropertyChanged("IsActive", oldValue, value);
                    }
                }
            }
        }  private bool _isActive = false;


        /// <summary>
        /// ID Created On.
        /// </summary>

        public DateTime? IDCreatedOn
        {
            get { return _idcreatedOn; }
            set
            {
                if (_idcreatedOn != value)
                {
                    if (OnPropertyChanging("IDCreatedOn", _idcreatedOn, value))
                    {
                        DateTime? oldValue = _idcreatedOn;
                        _idcreatedOn = value;
                        OnPropertyChanged("IDCreatedOn", oldValue, value);
                    }
                }
            }
        }  private DateTime? _idcreatedOn = null;


        /// <summary>
        /// Business Description.
        /// </summary>
        public string BusinessCategory
        {
            get { return __businesscategory; }
            set
            {
                if (__businesscategory != value)
                {
                    if (OnPropertyChanging("BusinessCategory", __businesscategory, value))
                    {
                        string oldValue = __businesscategory;
                        __businesscategory = value;
                        OnPropertyChanged("BusinessCategory", oldValue, value);
                    }
                }
            }
        }  private string __businesscategory = null;

        public string BusinessSubCategory
        {
            get { return __businessSubcategory; }
            set
            {
                if (__businessSubcategory != value)
                {
                    if (OnPropertyChanging("BusinessSubCategory", __businessSubcategory, value))
                    {
                        string oldValue = __businessSubcategory;
                        __businessSubcategory = value;
                        OnPropertyChanged("BusinessSubCategory", oldValue, value);
                    }
                }
            }
        }  private string __businessSubcategory = null;


        /// <summary>
        /// CompanyName.
        /// </summary>
        public string CompanyName
        {
            get { return _companyname; }
            set
            {
                if (_companyname != value)
                {
                    if (OnPropertyChanging("CompanyName", _companyname, value))
                    {
                        string oldValue = _companyname;
                        _companyname = value;
                        OnPropertyChanged("CompanyName", oldValue, value);
                    }
                }
            }
        }  private string _companyname = null;


        /// <summary>
        /// ContactPerson.
        /// </summary>
        public string ContactPerson
        {
            get { return _contactperson; }
            set
            {
                if (_contactperson != value)
                {
                    if (OnPropertyChanging("ContactPerson", _contactperson, value))
                    {
                        string oldValue = _contactperson;
                        _contactperson = value;
                        OnPropertyChanged("ContactPerson", oldValue, value);
                    }
                }
            }
        }  private string _contactperson = null;


        #endregion

        #endregion

        #region Public Methods

        #region CreateNew

        /// <summary>
        /// Creates a new, empty Directory object.
        /// </summary>
        public static Directory CreateNew()
        {
            Directory obj = new Directory();

            // Switch state to Added prior to initializing property values.
            obj.ObjState = ObjectState.Added;
            obj.IDCreatedOn = DateTime.Now;
            obj.IsActive = false;
            return (obj);
        }


        [MethodImpl(MethodImplOptions.Synchronized)]
        public static Directory CreateNew(DirectoryCollection collection)
        {
            Directory obj = CreateNew();

            // Get next/unique ID for the new object.
            int minVal = 0;
            foreach (Directory directory in collection)
            {
                if (directory.UserID < minVal)
                    minVal = directory.UserID;
            }
            obj.UserID = --minVal;
            collection.Add(obj);

            return (obj);
        }

        #endregion

        #region GetCompleteDirectory

        /// <summary>
        /// Returns a collection of Directory.
        /// </summary>
        public static DirectoryCollection GetCompleteDirectory()
        {
            DirectoryTableAdapter adapter = new DirectoryTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();

            dsDirectoryList.DirectoryDataTable tbl = adapter.GetData(null);

            DirectoryCollection list = new DirectoryCollection();

            if (tbl.Rows.Count > 0)
            {
                foreach (dsDirectoryList.DirectoryRow row in tbl.Rows)
                {
                    Directory directory = new Directory();
                    RelationalToObject(directory, row);
                    list.Add(directory);
                }
            }

            return (list);
        }

        #endregion

        #region GetDirectoryByID

        /// <summary>
        /// Returns an Directory object for the specified 'UserID' or null if no Directory with the specified parameter(s) exists.
        /// </summary>
        public static Directory GetDirectoryByID(int directoryid)
        {
            DirectoryTableAdapter adapter = new DirectoryTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();
            dsDirectoryList.DirectoryDataTable tbl = adapter.GetData(directoryid);

            if (tbl.Rows.Count == 1)
            {
                Directory directoryObj = new Directory();
                RelationalToObject(directoryObj, tbl.Rows[0]);
                return (directoryObj);
            }
            else if (tbl.Rows.Count > 1)
                throw new ApplicationException("Database integrity error: Specified 'userLogin' returned more than one User record.");

            return (null);
        }

        #endregion

        #region GetDirectoryByActiveStatus

        /// <summary>
        /// Returns an Directory object for the specified 'directory' or null if no User with the specified parameter(s) exists.
        /// </summary>
        public static DirectoryCollection GetDirectoryByActiveStatus(bool isActive)
        {
            DirectoryTableAdapter adapter = new DirectoryTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();

            dsDirectoryList.DirectoryDataTable tbl = adapter.GetDataByActiveStatus(isActive);

            DirectoryCollection list = new DirectoryCollection();

            if (tbl.Rows.Count > 0)
            {
                foreach (dsDirectoryList.DirectoryRow row in tbl.Rows)
                {
                    Directory directory = new Directory();
                    RelationalToObject(directory, row);
                    list.Add(directory);
                }
            }

            return (list);
        }

        #endregion

        #region GetDirectoryListByFirstName

        /// <summary>
        /// Returns an Directory List object for the specified 'firstname' or null if no name with the specified parameter(s) exists.
        /// </summary>
        public static Directory GetDirectoryListByFirstName(string firstname)
        {
            DirectoryTableAdapter adapter = new DirectoryTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();
            dsDirectoryList.DirectoryDataTable tbl = adapter.GetDataByFirstName(firstname);

            if (tbl.Rows.Count == 1)
            {
                Directory user = new Directory();
                RelationalToObject(user, tbl.Rows[0]);
                return (user);
            }
            else if (tbl.Rows.Count > 1)
                throw new ApplicationException("Database integrity error: Specified 'userLogin' returned more than one User record.");

            return (null);
        }

        #endregion

        #region GetDirectoryListByEmailAddres

        /// <summary>
        /// Returns an Directory List object for the specified 'emailaddres' or null if no name with the specified parameter(s) exists.
        /// </summary>
        public static Directory GetDirectoryListByEmailAddres(string emailaddres)
        {
            DirectoryTableAdapter adapter = new DirectoryTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();
            dsDirectoryList.DirectoryDataTable tbl = adapter.GetDataByEmailAddress(emailaddres);

            if (tbl.Rows.Count == 1)
            {
                Directory user = new Directory();
                RelationalToObject(user, tbl.Rows[0]);
                return (user);
            }
            else if (tbl.Rows.Count > 1)
                throw new ApplicationException("Database integrity error: Specified 'userLogin' returned more than one User record.");

            return (null);
        }

        #endregion

        #region Update

        /// <summary>
        /// Updates the specified Directory.
        /// </summary>
        public static void Update(Directory obj)
        {
            bool updateDirectory = false;

            // Do not update invalid objects.
            if (!obj.Validate())
            {
                StringBuilder sb = new StringBuilder(2048);
                sb.Append("The object being updated has one or more invalid properties; the Update() operation for this object has been cancelled.\nError(s):");
                foreach (ValidationError err in obj.Errors)
                    sb.Append("\n* " + err.Element + ": " + err.Message);

                throw new InvalidObjectException(sb.ToString());
            }
            else
            {
                updateDirectory = (obj.ObjState != ObjectState.Unchanged);

                if (!updateDirectory)
                    return;
            }

            ObjectState originalObjectState = obj.ObjState;
            
            dsDirectoryList.DirectoryDataTable tbl = null;
            if (updateDirectory)
            {
                
                DirectoryTableAdapter adapter = new DirectoryTableAdapter();
                adapter.Connection = AppSettings.GetDbConn();


                tbl = new dsDirectoryList.DirectoryDataTable();
                dsDirectoryList.DirectoryRow row = tbl.NewDirectoryRow();
                ObjectToRelational(obj, tbl, row);

                adapter.Update(tbl);

                if (originalObjectState == ObjectState.Deleted)
                    obj = null;
                else RelationalToObject(obj, tbl.Rows[0]);
            }
        }

        #endregion

        #region Validate

        /// <summary>
        /// Validates the object based on its properties at the time of the call; updates the Errors property.
        /// </summary>
        public override bool Validate()
        {
            Errors.Clear();

            if (ObjState == ObjectState.Unchanged)
            {
                // By definition, unchanged objects are valid.
                return (true);
            }
            else if (ObjState == ObjectState.Uninitialized)
            {
                Errors.Add(new ValidationError("object", "Object is uninitialized.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else if ((ObjState == ObjectState.Deleted))
            {
                // Deleted items must have 'real' (i.e. non-negative, non-zero) key(s) to be valid.
                Errors.Add(new ValidationError("UserID", "Deleted object has an invalid PKID.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else  // ObjState == Added | Modified
            {

            }

            return (Errors.Count == 0);
        }

        #endregion

        #region ToString

        /// <summary>
        /// User-friendly string represetation of this object.
        /// </summary>
        public override string ToString()
        {
            return (String.Format("Directory: UserID={0}, FirstName={1}, {2}", UserID, FirstName));
        }

        #endregion

        #endregion

    }

    /// <summary>
    /// Collection of 0 or more SubAdmin objects.
    /// </summary>

    public class DirectoryCollection : List<Directory>
    {
        #region Types

        public class UserComparer : IComparer<Directory>
        {
            public int Compare(Directory d1, Directory d2)
            {
                return (String.Compare(d1.FirstName, d2.FirstName));
            }
        }

        #endregion

        #region Public Methods

        #region FindByUserID

        public Directory FindByUserID(int userid)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].UserID == userid)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #region FindDirectoryByFirstName

        /// <summary>
        /// Case insensitve compare.
        /// </summary>
        public Directory FindDirectoryByFirstName(string firstname)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].FirstName == firstname)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #endregion

    }
}
